/* eslint-disable */
import React, { PureComponent } from 'react';
import { Spin, Select } from 'antd';
import _ from 'lodash';
import memoizeOne from 'memoize-one';
import { valueListByIndexCode } from '@/services/dict';

const dictCache = {};

const filterValue = (dicts, value) => _.find(dicts, d => d.code === value);
const memoizeGetValue = memoizeOne(filterValue);

async function getIndexValues(index) {
  const values = dictCache[index];
  if (values) return values;
  const { data } = await valueListByIndexCode({ indexCode: index });
  const newValues = data.map(d => ({ name: d.name, code: d.code }));
  dictCache[index] = newValues;
  return newValues;
}

async function getValueName(index, value) {
  const indexValues = await getIndexValues(index);
  const indexValue = memoizeGetValue(indexValues, value);
  return indexValue ? indexValue.name : value;
}

export class DictValue extends PureComponent {
  state = {
    loading: false,
    text: '',
  };

  componentDidMount() {
    const { index, value } = this.props;
    this.loadDate(index, value);
  }

  componentWillReceiveProps(nextProps) {
    const { index, value } = nextProps;
    const { props } = this;
    if (props.index !== index || props.value !== value) {
      this.loadDate(index, value);
    }
  }

  loadDate = (index, value) => {
    if (!value) {
      this.setState({ text: '', loading: false });
      return;
    }
    this.setState({ loading: true });
    getValueName(index, value).then(text => {
      this.setState({ text, loading: false });
    });
  };

  render() {
    const { loading, text } = this.state;
    return <span>{loading ? <Spin size="small" /> : `${text}`}</span>;
  }
}

const { Option } = Select;

export class DictSelect extends PureComponent {
  state = {
    data: [],
  };

  componentDidMount() {
    const { index } = this.props;
    getIndexValues(index).then(data => {
      this.setState({ data });
    });
  }

  render() {
    const { props } = this;
    const { data } = this.state;
    return (
      <Select placeholder="请选择" {...props}>
        {data.map(item => (
          <Option key={item.code} value={item.code}>
            {item.name}
          </Option>
        ))}
      </Select>
    );
  }
}
